package common

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"go_demo_1/conf"
	"log"
	"sync"
)
/*
CREATE DATABASE db_go DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
* MysqlConnectiPool
* 数据库连接操作库
* 基于gorm封装开发
 */
type MysqlConnectiPool struct {
}

var instance *MysqlConnectiPool
var once sync.Once

var Db *gorm.DB
var err_db error
func GetInstance() *MysqlConnectiPool {
	once.Do(func() {
		instance = &MysqlConnectiPool{}
	})
	return instance
}

/*
* @fuc 初始化数据库连接(可在mail()适当位置调用)
 */
func (m *MysqlConnectiPool) InitDataPool() (issucc bool) {
	dbConf := conf.Conf.DataBase
	Db, err_db = gorm.Open("mysql", fmt.Sprintf(
		"%s:%s@(%s:%s)/%s?charset=%s&parseTime=True&loc=Local",
		dbConf.Username, dbConf.Password,dbConf.Host, dbConf.Port,  dbConf.DbName,dbConf.Charset))
	//fmt.Println(err_db)
	if err_db != nil {
		log.Fatal(err_db)
		return false
	}
	//关闭数据库，db会被多个goroutine共享，可以不调用
	//defer Db.Close()
	return true
}

func init() {
	//init的加载顺序比main还高，所以在init进行数据库实例化的时候，是优先级比较高的
	//fmt.Println("mysql content in init")
	//dbConf := conf.Conf.DataBase
	//var err error
	//Db, err := gorm.Open("mysql", fmt.Sprintf(
	//	"%s:%s@(%s:%s)/%s?charset=%s&parseTime=True&loc=Local",
	//	dbConf.Username, dbConf.Password,dbConf.Host, dbConf.Port,  dbConf.DbName,dbConf.Charset))
	//if err != nil {
	//	log.Fatalln(Db,"======",err)
	//}
	//关闭数据库，db会被多个goroutine共享，可以不调用
	//defer Db.Close()
}


